package timing.ukulele.third.service.msg;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import timing.ukulele.data.third.data.msg.ChannelAccountGroupDTO;
import timing.ukulele.data.third.view.msg.ChannelAccountGroupVO;
import timing.ukulele.third.convertor.msg.ChannelAccountGroupConverter;
import timing.ukulele.third.exception.ThirdServiceException;
import timing.ukulele.third.mapper.msg.ChannelAccountGroupMapper;
import timing.ukulele.third.persistent.msg.ChannelAccountGroup;
import timing.ukulele.third.service.common.BaseOperatorService;
import java.util.List;

/**
 * @Description 概要描述
 * @Author zh
 * @Date 2025-10-13 16:38
 */
@Service
public class ChannelAccountGroupService extends BaseOperatorService<ChannelAccountGroupMapper, ChannelAccountGroup> {

    public Boolean addChannelAccountGroup(ChannelAccountGroupDTO dto) {
        validateWriteOperation(dto);
        ChannelAccountGroup channelAccountGroup = ChannelAccountGroupConverter.INSTANCE.d2p(dto);
        return this.save(channelAccountGroup);
    }

    private void validateWriteOperation(ChannelAccountGroupDTO dto) {
        if (this.lambdaQuery()
                .eq(ChannelAccountGroup::getName, dto.getName())
                .notIn(dto.getId() != null, ChannelAccountGroup::getId, dto.getId()).count() > 0) {
            throw new ThirdServiceException("名称已存在，请勿重复添加");
        }
    }

    public Boolean updateChannelAccountGroup(ChannelAccountGroupDTO dto) {
        validateWriteOperation(dto);
        ChannelAccountGroup channelAccountGroup = ChannelAccountGroupConverter.INSTANCE.d2p(dto);
        return this.updateById(channelAccountGroup);
    }

    public Boolean deleteChannelAccountGroup(Long id) {
        return this.lambdaUpdate().set(ChannelAccountGroup::getDeleted, Boolean.TRUE)
                .eq(ChannelAccountGroup::getId, id).update();
    }

    public IPage<ChannelAccountGroupVO> pageList(ChannelAccountGroupDTO dto) {
        Page pageParam = new Page(dto.getCurrent(), dto.getPageSize());
        Page page = this.lambdaQuery()
                .eq(ChannelAccountGroup::getDeleted, Boolean.FALSE)
                .like(StrUtil.isNotBlank(dto.getName()), ChannelAccountGroup::getName, dto.getName())
                .page(pageParam);
        List list = ChannelAccountGroupConverter.INSTANCE.p2vList(page.getRecords());
        page.setRecords(list);
        return page;
    }

}
